package main

import (
	"fmt"
	"strconv"
)

// This is the interface that allows for creating nested lists.
// You should not implement it, or speculate about its implementation
type NestedInteger struct {
	value     int
	list      []*NestedInteger
	isInteger bool
}

// Return true if this NestedInteger holds a single integer, rather than a nested list.
func (n NestedInteger) IsInteger() bool {
	return n.isInteger
}

// Return the single integer that this NestedInteger holds, if it holds a single integer
// The result is undefined if this NestedInteger holds a nested list
// So before calling this method, you should have a check
func (n NestedInteger) GetInteger() int {
	return n.value
}

// Set this NestedInteger to hold a single integer.
func (n *NestedInteger) SetInteger(value int) {
	n.value = value
}

// Set this NestedInteger to hold a nested list and adds a nested integer to it.
func (n *NestedInteger) Add(elem NestedInteger) {
	n.list = append(n.list, &elem)
}

// Return the nested list that this NestedInteger holds, if it holds a nested list
// The list length is zero if this NestedInteger holds a single integer
// You can access NestedInteger's List element directly if you want to modify it
func (n NestedInteger) GetList() []*NestedInteger {
	return n.list
}

func deserialize(s string) *NestedInteger {
	return _deserialize(s, 0, len(s)-1)
}

func _deserialize(s string, l int, r int) *NestedInteger {
	fmt.Println(s[l : r+1])
	//纯数字
	if s[l] != '[' {
		num := convertInt(s, l, r)
		return newIntNestedInteger(num)
	}
	//列表
	ni := newIntNestedList()
	status := 0
	i := l + 1
	curLeft := l + 1
	for ; i <= r-1; i++ {
		if s[i] == '[' {
			status--
		}
		if s[i] == ']' {
			status++
		}
		if status == 0 && s[i] == ',' {
			//fmt.Println(s[curLeft:i])
			tmp := _deserialize(s, curLeft, i-1)
			ni.Add(*tmp)
			curLeft = i + 1
		}
	}
	if curLeft <= r-1 {
		tmp := _deserialize(s, curLeft, r-1)
		ni.Add(*tmp)
	}
	return ni
}

func newIntNestedInteger(value int) *NestedInteger {
	ni := new(NestedInteger)
	ni.SetInteger(value)
	ni.isInteger = true
	return ni
}

func newIntNestedList() *NestedInteger {
	ni := new(NestedInteger)
	ni.list = []*NestedInteger{}
	ni.isInteger = false
	return ni
}

func convertInt(s string, l int, r int) int {
	subStr := s[l : r+1]
	res, _ := strconv.Atoi(subStr)
	return res
}

func (n NestedInteger) String() string {
	if n.IsInteger() {
		return strconv.Itoa(n.GetInteger())
	}
	s := "["
	for i, ni := range n.list {
		s += ni.String()
		if i != len(n.list)-1 {
			s += ","
		}
	}
	s += "]"
	return s
}

func main() {
	s := "[123,[456,[789]]]"
	fmt.Println("--")
	res := deserialize(s)
	fmt.Println("--")
	fmt.Println(res)

}
